<template>
  <div ref="container" class="scene-container"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as THREE from "three";
import textureImage from "../assets/473ee8a12b93506ecb0ae4f17ce9a188.png";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 导入GSAP
import gsap from "gsap";
//导入dat.gui
import * as dat from "dat.gui";

import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader";

//给当前组件一个名称，使用defineOptions定义
defineOptions({
  name: "ThreeScene",
});

const container = ref<HTMLElement>();
let scene: THREE.Scene;
let camera: THREE.PerspectiveCamera;
let renderer: THREE.WebGLRenderer;
let cube: THREE.Mesh;
//声明轨道控制器
let controls: OrbitControls;
const initScene = () => {
  //创建场景
  scene = new THREE.Scene();
  //创建相机
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  //创建渲染器
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.value?.appendChild(renderer.domElement);
  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.05;
  //创建坐标轴
  const axesHelper = new THREE.AxesHelper(5);
  scene.add(axesHelper);
  camera.position.set(0, 0, 10);
  scene.add(camera);
  //设置cube
  const cubeGeometry = new THREE.CubeTextureLoader();
  //   const envMapTexture = cubeGeometry.load([]);
  //加载hdr环境图
  const rbgLoader = new RGBELoader();
  const envMapTexture = rbgLoader.load(
    "venetian_crossroads_4k.hdr",
    (texture) => {
      texture.mapping = THREE.EquirectangularReflectionMapping;
      scene.background = texture;
      scene.environment = texture;
    }
  );
  //球体
  const sphereGeometry = new THREE.SphereGeometry(1, 20, 20);
  //材质
  const material = new THREE.MeshStandardMaterial({
    metalness: 1,
    roughness: 0.1,
    envMap: envMapTexture,
  });
  const sphere = new THREE.Mesh(sphereGeometry, material);
  scene.add(sphere);

  scene.background = envMapTexture;
  const light = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(light);
  // //灯光--平行光
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
  directionalLight.position.set(10, 10, 10);
  scene.add(directionalLight);
  // 添加轨道控制器
  controls = new OrbitControls(camera, renderer.domElement);
  animate();
};
onMounted(() => {
  initScene();
});
// 添加动画循环函数
const animate = () => {
  requestAnimationFrame(animate);
  // 更新控制器
  controls.update();
  // 渲染场景
  renderer.render(scene, camera);
};
</script>
